package com.taotao.manage.controller;

import com.taotao.manage.pojo.ItemCatTree;
import com.taotao.manage.service.ItemCatTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/item/cat")
public class ItemCatController {

    @Autowired
    private ItemCatTreeService itemCatTreeService;

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<ItemCatTree>> queryItemCatTree(@RequestParam(value = "id",defaultValue = "0")Long parent_id){
        try {
            if (parent_id.longValue()<0){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            }
            ItemCatTree record = new ItemCatTree();
            record.setParentId(parent_id);
            List<ItemCatTree> list = itemCatTreeService.queryListByWhere(record);
            if (CollectionUtils.isEmpty(list)){
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @RequestMapping(value = "all",method = RequestMethod.GET)
    public ResponseEntity<Map<String,String>> queryAll(){
        try {
            List<ItemCatTree> itemCatTrees = itemCatTreeService.queryAll();
            if (CollectionUtils.isEmpty(itemCatTrees)){
                return ResponseEntity.notFound().build();
            }
            Map<String, String> map = new HashMap<>();
            for (ItemCatTree itemCatTree:itemCatTrees){
                map.put(itemCatTree.getId()+"",itemCatTree.getName());
            }
            return ResponseEntity.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

    }

}
